package com.example.frn.controller;

import com.example.frn.dto.LoginDto;
import com.example.frn.entity.User;
import com.example.frn.service.UserService;
import com.example.frn.util.JwtUtil;
import com.example.frn.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1")
public class LoginController {

    @Autowired
    private UserService userService;
    @PostMapping("/user/login")
    public R userLogin(@RequestBody LoginDto dto){
        User loginUser = userService.login(dto.getUsername(), dto.getPasswd());
        if(loginUser !=null){
            Map<String,String> claims = new HashMap<>();
            claims.put("id",loginUser.getId().toString());
            claims.put("username",loginUser.getUsername());
            claims.put("nickName",loginUser.getNickName());
            String token = JwtUtil.build(claims);
            claims.put("token",token);
            return R.ok(claims);

        } else {
            return new R(401,"用户名或密码错误",null);
        }
    }
}
